import BaseModel from './MongoBaseModel';

export interface UnionType {
  id?: any;
  project_name?: string;
  project_id?: number | string;
  developer?: string;
  branch?: string;
  checkStatus?: number;
  env?: string;
  isMergeToMain?: number | undefined;
  isMergeToUnion?: number | undefined;
  mr?: string | undefined;
  review_status?: number;
  unionBranch?: string;
  $or?: any;
  online_time?: string;
  children?: any[];
  pid?: string;
  [key: string]: any;
}

class Model extends BaseModel<UnionType> {
  constructor() {
    super('storyWithproject');
  }

  async updateMany(data, query) {
    const db = await this.init();
    return db.updateMany(query, {
      $set: data,
    });
  }

  async getStoryWithProject(params) {
    const db = await this.init();
    const ret = db.aggregate([
      {
        $lookup: {
          from: 'projects',
          localField: 'project_id',
          foreignField: 'id',
          as: 'defineField',
        },
      },
      {
        $match: {
          ...params,
        },
      },
      {
        $unwind: '$defineField',
      },
      {
        $project: {
          branch: 1,
          developer: 1,
          env: 1,
          http_url_to_repo: 1,
          id: 1,
          isEdit: 1,
          pid: 1,
          project_id: 1,
          project_name: 1,
          review_status: 1,
          _id: 1,
          envList: '$defineField.envs',
          type: 1,
        },
      },
    ]);
    return ret.toArray();
  }

  async getListAll() {
    const db = await this.init();
    // const ret = db.find({});
    const ret = db.aggregate([
      {
        $lookup: {
          from: 'storys',
          localField: 'id',
          foreignField: 'id',
          as: 'defineField',
        },
      },
      {
        $match: {
          'defineField.status': { $nin: ['status_5', 'status_7', 'status_8', 'status_38', 'status_39', 'status_40'] },
          unionBranch: { $exists: false },
        },
      },
      {
        $unwind: '$defineField',
      },
      {
        $unwind: '$env',
      },
      {
        $project: {
          id: 1,
          project_id: 1,
          project_name: 1,
          branch: 1,
          env: 1,
          developer: 1,
          type: 1,
          parentid: 1,
          online_time: '$defineField.online_time',
        },
      },
    ]);
    return ret.toArray();
  }
}

export default new Model();
